import { createUniFetch } from 'uni-app-fetch'
import { useUserStore } from '@/stores/user.js'

const tabBarPagePaths = [
  'pages/task/index',
  'pages/my/index',
  'pages/message/index',
]

// 1. 创建一个网络请求实例对象
const uniFetch = createUniFetch({
  loading: { title: '正在加载中...' },
  baseURL: 'https://slwl-api.itheima.net',
  intercept: {
    // 1.1 请求拦截器
    request(options) {
      // 1.1.1 统一携带token
      const store = useUserStore()
      const defaultHeader = {}
      if (store.token) defaultHeader.Authorization = store.token
      options.header = Object.assign(defaultHeader, options.header)
      return options
    },
    // 1.2 响应拦截器
    response({ statusCode, data }) {
      // 1.2.1 判断token失效
      if (statusCode === 401) {
        const stackPage = getCurrentPages()
        const currentPage = stackPage[stackPage.length - 1]
        const redirectURL = currentPage.route
        // 1.2.2 确定跳转方式
        const routerType = tabBarPagePaths.includes(redirectURL)
          ? 'switchTab'
          : 'redirectTo'
        return uni.redirectTo({
          url: `/pages/login/index?redirectURL=/${redirectURL}&routerType=${routerType}`,
        })
      }
      return data
    },
  },
})

// 2. 导出请求实例对象
export default uniFetch
